import requests
from bs4 import BeautifulSoup

base_url = "http://www.ncmbio.com"
headers = {
    "Referer": "http://www.ncmbio.com",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}


def get_prodes(url: str):
    response = requests.get(url, headers=headers)
    return BeautifulSoup(response.text, "html.parser")


def extract_prodes(soup: BeautifulSoup) -> BeautifulSoup:
    # 选择所有img,给 src 添加 base_url（仅限非 http/https 开头的 src）
    des_dom = soup.find("div", attrs={"class": "tab-content entry"})
    for img in des_dom.find_all("img"):
        src = img.get("src", "")
        if not src.startswith(("http://", "https://")):
            img["src"] = base_url + src
    return des_dom


def search_ncmbio(keyword: str) -> str:
    """
    用于商品搜索，只返回 response.text
    :param keyword: 搜索关键词
    :return: 搜索结果页面的 HTML 文本
    """
    url = "http://www.ncmbio.com/search.html"
    params = {"keyword": keyword}
    response = requests.get(url, headers=headers, params=params)
    return response.text


def extract_product_links(html: str) -> str | None:
    soup = BeautifulSoup(html, "html.parser")
    ul = soup.find("ul", class_="prolist")
    if ul:
        for li in ul.find_all("li"):
            a_tag = li.find("a")
            if a_tag and a_tag.has_attr("href"):
                # links.append(a_tag["href"])
                return base_url + a_tag["href"]
        return None
    return None


def extract_img_url(soup: BeautifulSoup) -> list[dict] | None:
    pic_scroll_divs = soup.find_all("div", class_="pic-scroll")
    for div in pic_scroll_divs:
        images = div.find_all("img")
        _list = []
        for img in images:
            src_url = img.get("src")
            if not src_url.startswith(("http://", "https://")):
                _list.append({"photo": base_url + src_url})
            else:
                _list.append({"photo": src_url})
        return _list
    return None


def get_website_process(procode: str) -> str:
    search_html = search_ncmbio(procode)
    if url := extract_product_links(search_html):
        prodes = get_prodes(url)
        prodes_dom = extract_prodes(prodes)
        img_url = extract_img_url(prodes)
        return str(prodes_dom), img_url
    return None


if __name__ == "__main__":
    res = get_website_process("P10300")
    print(res)
    # img_url = extract_img_url(res)
    # print(img_url)
